package com.cyjt.operation.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MotionEventCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.Date;

import com.cyjt.operation.R;
import com.cyjt.operation.base.AppConfig;
import com.cyjt.operation.bean.ParkingLot;

/**
 * 路段
 */
public class ParkingSpaFragment extends Fragment {
    private static final String ARG_PARAM_PARKINGSPS = "parkingsps";

    private ArrayList<ParkingLot> parkingSps;

    private OnParkingSpaFragmentInteractionListener mListener;

    public static ParkingSpaFragment newInstance(ArrayList<ParkingLot> parkingSps) {
        ParkingSpaFragment fragment = new ParkingSpaFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM_PARKINGSPS, parkingSps);
        fragment.setArguments(args);
        return fragment;
    }

    public static ParkingSpaFragment newInstance() {
        ParkingSpaFragment fragment = new ParkingSpaFragment();
        return fragment;
    }

    public ParkingSpaFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            parkingSps = (ArrayList<ParkingLot>) getArguments().getSerializable(ARG_PARAM_PARKINGSPS);
        }
    }

    public void setBlueToothTips(boolean connected) {
        if (connected) {
            textView_tips_bluetooth_status.setText("已连接");
        } else {
            textView_tips_bluetooth_status.setText("连接蓝牙");
        }
    }

    private View rootView;
    private LayoutInflater inflater;
    private LinearLayout layout_root;
    private EditText textView_filter_view;
    private TextView textView_tips_bluetooth_status;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.inflater = inflater;
        if (rootView != null) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null)
                parent.removeView(rootView);
            return rootView;
        }
        rootView = inflater.inflate(R.layout.fragment_layout_parkingsp, container, false);
        textView_tips_bluetooth_status = (TextView) rootView.findViewById(R.id.textView_tips_bluetooth_status);
        layout_root = (LinearLayout) rootView.findViewById(R.id.layout_root);
        rootView.setOnTouchListener(new View.OnTouchListener() {
            boolean returnFlag = false;
            private float rawX = 0;
            private float x = 0;
            private long time = 0;
            private long lastDate = 0;
            private float speed;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (MotionEventCompat.getActionMasked(event)) {
                    case MotionEvent.ACTION_DOWN:
                        rawX = event.getRawX();
                        if (rawX < 10) {
//                            returnFlag = AppConfig.openFrameLayoutScrollRight;
                            lastDate = new Date().getTime();
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (returnFlag) {
                            x = event.getX();
                            time = new Date().getTime();
                            speed = (event.getRawX() - rawX) / (time - lastDate);
                            lastDate = time;
                            rawX = event.getRawX();
                            mListener.onFragmentParMove(x, rawX);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (returnFlag) {
                            returnFlag = false;
                            mListener.onFragmentParMoveFinished(rawX, speed);
                        }
                        break;
                }
                return returnFlag;
            }
        });
        rootView.findViewById(R.id.button_buletooth).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开蓝牙部分
                mListener.openBlueTooth();
            }
        });
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        upDistrictsData();
    }

    //更改节点状态
    public void upParkingSensorStatus(ParkingLot parkingSpa, int index) {
//        parkingSps.set(index, parkingSpa);
        if (layout_root == null)
            return;
        layout_root.getChildAt(index).findViewById(R.id.textView_binding).setVisibility(View.VISIBLE);
        ((TextView) (layout_root.getChildAt(index).findViewById(R.id.textView_binding))).setText("节点正在设置...");
    }

    //更改节点状态
    public void upParkingSensorStatusFinished(ParkingLot parkingSpa, int index) {
        if (layout_root == null)
            return;
        for (int i = 0; i < parkingSps.size(); i++) {
            if (parkingSps.get(i).getSensorCode().equals(parkingSpa.getSensorCode())) {
                index = i;
                layout_root.getChildAt(index).findViewById(R.id.textView_binding).setVisibility(View.VISIBLE);
                ((TextView) (layout_root.getChildAt(index).findViewById(R.id.textView_binding))).setText("节点设置成功!");
                mListener.bindingFinishedRespose(parkingSps.get(i));
                break;
            }
        }
    }

    public void upParkingSpas(ArrayList<ParkingLot> parkingSpas) {
        this.parkingSps = parkingSpas;
        upDistrictsData();
    }

    public void upParkingSpa(ParkingLot parkingSpa, int index) {
        parkingSps.set(index, parkingSpa);
        if (layout_root == null)
            return;
        upDistrictsData((RelativeLayout) layout_root.getChildAt(index), parkingSpa, index);
    }

    public void startProgress() {
        layout_root.removeAllViews();
    }

    private RelativeLayout view;

    private void upDistrictsData() {
        if (parkingSps == null)
            return;
        if (layout_root == null)
            return;
        layout_root.removeAllViews();
        for (int i = 0; i < parkingSps.size(); i++) {
            view = (RelativeLayout) inflater.inflate(R.layout.layout_parking_spa, null);
            layout_root.addView(upDistrictsData(view, parkingSps.get(i), i));
        }
    }

    private RelativeLayout upDistrictsData(RelativeLayout view, ParkingLot parkingSp, int index) {
        view.setId(index);
        view.setTag(parkingSp);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onParkingSpaBeChecked((ParkingLot) v.getTag(), v.getId());
            }
        });
        ((TextView) view.findViewById(R.id.textView_title)).setText(parkingSp.getCode() + "");
        if (parkingSp.getSensorCode() == null || parkingSp.getSensorCode().equals("")) {
            ((ImageView) view.findViewById(R.id.imageView_status)).setImageResource(R.drawable.icon_color_gr);
        } else {
            ((ImageView) view.findViewById(R.id.imageView_status)).setImageResource(R.drawable.icon_color_vividgreen);
        }
        view.findViewById(R.id.textView_binding).setVisibility(View.INVISIBLE);
        return view;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnParkingSpaFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnParkingSpaFragmentInteractionListener {

        public void onParkingSpaBeChecked(ParkingLot parkingSpa, int index);

        public void onFragmentParMove(float x, float rawX);

        public void onFragmentParMoveFinished(float rawX, float speed);

        public void openBlueTooth();

        public void bindingFinishedRespose(ParkingLot parkingSpa);

    }

}
